package com.tuyan.aixiang.activity.home.me;

import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tuyan.aixiang.BuildConfig;
import com.tuyan.aixiang.MainApplication;
import com.tuyan.aixiang.R;
import com.tuyan.aixiang.activity.channel.ChannelActivity;
import com.tuyan.aixiang.api.HttpClient;
import com.tuyan.aixiang.api.helper.ResultTransformer;
import com.tuyan.aixiang.api.helper.RxSchedulers;
import com.tuyan.aixiang.common.AppData;
import com.tuyan.aixiang.common.BaseFragment;
import com.tuyan.aixiang.common.BasePresenter;
import com.tuyan.aixiang.common.Constant;
import com.tuyan.aixiang.common.StorageKey;
import com.tuyan.aixiang.component.MenuItem;
import com.tuyan.aixiang.model.VersionResult;
import com.tuyan.aixiang.receiver.MessageHandler;
import com.tuyan.aixiang.util.StorageUtil;
import com.tuyan.aixiang.util.StringUtil;
import com.tuyan.aixiang.util.ToastUtil;
import com.videogo.openapi.EZOpenSDK;

import androidx.fragment.app.Fragment;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class MeFragment extends BaseFragment {

    @BindView(R.id.iv_edit)
    ImageView ivEdit;

    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;

    @BindView(R.id.tv_nickname)
    TextView tvNickname;

    @BindView(R.id.tv_mobile)
    TextView tvMobile;

    @BindView(R.id.ll_container)
    LinearLayout llContainer;

    @BindView(R.id.ll_menu_wrapper)
    LinearLayout llMenuWrapper;

    @BindView(R.id.ll_logout)
    LinearLayout llLogout;

    MenuItem backupMobile;

//    @BindView(R.id.ll_cancel_account)
//    GeneralRoundLinearLayout llCancelAccount;

    @Override
    protected void initView(View contentView) {
        ivEdit.setOnClickListener(v -> {
            openWeb(Constant.ME_EDIT);
        });

        resetUserData();
        AppData.addUserDataChangeCallback("meFragment", this::resetUserData);

        // add menu     qkaq2   QK123456@
        llMenuWrapper.removeAllViews();
        MenuItem friend = new MenuItem(getContext());
        friend.setUp(R.string.menu_friend, R.drawable.icon_friend, true);
        friend.setOnClickListener(v -> openWeb(Constant.ME_FRIEND));
        MenuItem sharedDevice = new MenuItem(getContext());
        sharedDevice.setUp(R.string.menu_share_device, R.drawable.icon_share_device, false).bottomGap();
        sharedDevice.setOnClickListener(v -> openWeb(Constant.ME_SHARE_DEVICE));
        MenuItem about = new MenuItem(getContext());
        about.setUp(R.string.menu_about, R.drawable.icon_about, true);
        about.setOnClickListener(v -> openWeb(Constant.ME_ABOUT));
        MenuItem update = new MenuItem(getContext());
        update.setUp(R.string.menu_update, R.drawable.icon_update, true);
        update.setOnClickListener(v -> this.checkUpdate());
        MenuItem help = new MenuItem(getContext());
        help.setUp(R.string.menu_help, R.drawable.icon_help, false).bottomGap();
        help.setOnClickListener(v -> openWeb(Constant.HELP_INDEX));

        MenuItem setting  = new MenuItem(getContext());
        setting.setUp(R.string.op_setting, R.drawable.icon_setting, true).bottomGap();
        setting.setOnClickListener(v -> openWeb(Constant.ME_SETTING));


//        backupMobile = new MenuItem(getContext());
//
//        backupMobile.setUp(getBkPhoneTitle(), R.drawable.icon_phone, false).bottomGap();
//        backupMobile.setOnClickListener(v -> openWeb(Constant.HELP_BACKUP_MOBILE));

        llMenuWrapper.addView(friend);
        llMenuWrapper.addView(sharedDevice);
        llMenuWrapper.addView(about);
        llMenuWrapper.addView(update);
        llMenuWrapper.addView(help);

        llMenuWrapper.addView(setting);


        // TODO remove
        if(BuildConfig.DEBUG) {
            MenuItem testRing = new MenuItem(getContext());
            testRing.setUp("dingdong", R.drawable.icon_phone, true);
            testRing.setOnClickListener(v -> MessageHandler.onMessage(getContext()));


            MenuItem volup = new MenuItem(getContext());
            volup.setUp("vol up", R.drawable.icon_phone, true);
            volup.setOnClickListener(v -> {
                StorageUtil.setInt(StorageKey.NOTICE_SOUND, Constant.NOTICE_SOUND_TYPE_IMPORTANT);
            });
            MenuItem voldown = new MenuItem(getContext());
            voldown.setUp("vol down", R.drawable.icon_phone, true);
            voldown.setOnClickListener(v -> {
                StorageUtil.setInt(StorageKey.NOTICE_SOUND, Constant.NOTICE_SOUND_TYPE_DEFAULT);
            });
            llMenuWrapper.addView(testRing);
            llMenuWrapper.addView(volup);
            llMenuWrapper.addView(voldown);
        }
//        llMenuWrapper.addView(backupMobile);

    }

    private String getBkPhoneTitle() {
        String t = getString(R.string.menu_backup_mobile);
        String markPhone = AppData.getUserInfo().getMarkPhone();
        if(!StringUtil.isBlank(markPhone)) {
            t += "(" + markPhone +")";
        }
        return t;
    }

    private void checkUpdate() {
        showLoading();
        Disposable disposable = HttpClient.getVersion().checkVersion(1).compose(RxSchedulers.io_main())
                .compose(ResultTransformer.handleResult())
                .subscribe(data -> {
                    hideLoading();
                    if(null != data.get()) {
                        VersionResult result = data.get();
                        Integer version = result.getVeersion();
                        Integer localVersion = BuildConfig.VERSION_CODE;
                        if(localVersion < version) {
                            openApplicationMarket(Constant.PACKAGE_NAME);
                        } else {
                            ToastUtil.makeShort("当前已是最新版本");
                        }
                    } else {
                      ToastUtil.makeShort("检查更新失败");
                    }
                }, throwable -> {
                    ToastUtil.makeShort("检查更新失败");
                    hideLoading();
                });
        addDisposable(disposable);
    }

    private void openApplicationMarket(String packageName) {
        try {
            String str = "market://details?id=" + packageName;
            Intent localIntent = new Intent(Intent.ACTION_VIEW);
            localIntent.setData(Uri.parse(str));
            startActivity(localIntent);
        } catch (Exception e) {
            // 打开应用商店失败 可能是没有手机没有安装应用市场
            e.printStackTrace();
            ToastUtil.makeShort("打开应用商店失败");
            // 调用系统浏览器进入商城
        }
    }


    private void resetUserData() {
        // set user info
        tvNickname.setText(AppData.getUserInfo().getNickname());
        tvMobile.setText(AppData.getUserInfo().getMobile());
        loadImage(AppData.getUserInfo().getHeadimg(), ivAvatar);
        if(null != backupMobile) {
            backupMobile.setTitle(getBkPhoneTitle());
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_me;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

//    @OnClick(R.id.ll_cancel_account)
//    public void cancelAccount() {
//
//    }

    @OnClick(R.id.ll_logout)
    public void logout() {

       Disposable disposable =  HttpClient.getAccount().logout().compose(RxSchedulers.io_main()).compose(ResultTransformer.handleResult())
                .subscribe(r -> {
                    doLogout();
                }, throwable -> {
                    doLogout();
                });
       addDisposable(disposable);
    }

    private void doLogout() {
        AppData.clearNoticeCountChangeCallback();
        AppData.clearUserDataChangeCallback();
        AppData.clearAll();
        MainApplication.unBindAccount();
        EZOpenSDK.getInstance().logout();
        Intent intent = new Intent(getContext(), ChannelActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        getContext().startActivity(intent);
        getActivity().finish();
    }

    @Override
    public void onResume() {
        super.onResume();

    }
}
